package cn.funeralobjects.aoss.utils;

import cn.funeralobjects.ams.web.api.ProductApiApi;
import cn.funeralobjects.common.service.exception.LackDataException;
import cn.funeralobjects.utils.aliyun.core.model.AliyunAction;
import cn.funeralobjects.utils.aliyun.oss.AliyunOssClient;
import cn.funeralobjects.utils.aliyun.oss.AliyunOssClientFactory;
import reactor.core.publisher.Mono;

/**
 * @author FuneralObjects
 * Create date: 2020/6/8 4:29 PM
 */
public class BucketUtils {
    public static Mono<AliyunOssClient> getOssClient(String prodResCode, AliyunAction aliyunAction, ProductApiApi productApiApi) {
        return BucketUtils.getOssClient(prodResCode, aliyunAction, productApiApi, null);
    }

    public static Mono<AliyunOssClient> getOssClient(String prodResCode, AliyunAction aliyunAction, ProductApiApi productApiApi, String regionId) {
        return productApiApi
                .getExistsAccessKey(prodResCode, aliyunAction.getAction(), aliyunAction.getVersion())
                .map((vProductResAccessKey) -> new AliyunOssClientFactory(aliyunAction.getDomain(), vProductResAccessKey.getAccessKeyId(), vProductResAccessKey.getAccessKeySecret()).createClient(regionId == null ? vProductResAccessKey.getRegionId() : regionId))
                .switchIfEmpty(Mono.error(new LackDataException(String.format("The ProductRes[%s] with AccessKey doesn't exists!", prodResCode))));

    }
}
